let redisClient = require('../../redis').redisClient;
let RedisKey = require('./RedisKey')
var _ = require('underscore');
let AV = require('leanengine');



/**
 * 把用户信息缓存到session里面
 * @param user
 * @param sessionToken
 */
function pushUserToCacheBySessionToken(user,sessionToken) {
    let key = RedisKey.redisUserWidthSessionToken(sessionToken)

    redisClient.hmsetAsync(key,  JSON.parse(JSON.stringify(user))).catch(function(err) {
        console.error(err.stack);
        console.error(err)
    });
}

function getUserToCacheBySessionToken(sessionToken){
   return redisClient.hgetallAsync(RedisKey.redisUserWidthSessionToken(sessionToken)).then(function(result) {



       let user = new AV.User.createWithoutData('_User',result.objectId)

       user.setUsername(result.mobilePhoneNumber )
       user.set('nickName',result.nickName)
       user.set('mobilePhoneNumber',result.mobilePhoneNumber)
       user.set('idCard',result.idCard)
       user.set('weChat',result.weChat)
       user.set('mobilePhoneVerified',result.mobilePhoneVerified)
       user.setMobilePhoneNumber(result.mobilePhoneNumber)
       user.set('name',result.name)


       return user
    }).catch(error =>{
        return error
   });
}

/* 用于序列化 AVObject 的辅助函数 */
function stringifyAVObject(object) {
    return JSON.stringify(_.omit(object.toJSON(), '__before', '__after'))
}

module.exports = {
    pushUserToCacheBySessionToken:pushUserToCacheBySessionToken,
    getUserToCacheBySessionToken:getUserToCacheBySessionToken
}